<template>
    <section>
        <div class="cate-container">
            <div class="header">
                <h4>发布商品</h4>
            </div>
            <div class="cate-con">
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm">

                    <form-row :label="`商品名称`" :required="true" class="flex-box">
                        <el-form-item slot="item" class="form-row__item" prop="name">
                            <el-input v-model="ruleForm.name" placeholder="请输入商品名称"></el-input>
                        </el-form-item>
                        <div slot="info-item" class="form-row__item_info">建议：品牌 + 商品内容 + 规格</div>
                    </form-row>

                    <form-row :label="`商品简介`" :required="true">
                        <el-form-item slot="item" class="form-row__item" prop="desc">
                            <el-input v-model="ruleForm.desc" placeholder="请输入商品简介"></el-input>
                        </el-form-item>
                        <div slot="info-item" class="form-row__item_info">建议：简介并具有吸引力的文章</div>
                    </form-row>
                    <form-row label="商品主图" :required="true" prop="slideshows">
                        <div style="flex-direction:column;" class="flex-box">
                            <image-upload :imageList.sync="ruleForm.slideshows" :clearList="clearList"
                                          :imgNum="5">
                                <div slot="tip" class="image-info">尺寸750*600，支持jpg、png文件，5张上限</div>
                            </image-upload>
                            <!--<div slot="tip" class="image-info">尺寸750*600，支持jpg、png文件，5张上限</div>-->
                        </div>
                    </form-row>
                    <form-row label="商品详情图" :required="true" prop="image">
                        <div style="flex-direction:column;" class="flex-box">
                            <upload :image.sync="ruleForm.image" :clearList="clearList">
                                <div slot="tip" class="image-info">尺寸宽度不低于640，高度不限制，支持jpg、png文件，1张上限</div>
                            </upload>
                            <!--<image-upload :imageList.sync="ruleForm.image" :clearList="clearList"-->
                            <!--:imgNum="1">-->
                            <!--<div slot="tip" class="image-info">尺寸宽度不低于640，高度不限制，支持jpg、png文件，1张上限</div>-->
                            <!--</image-upload>-->

                        </div>
                    </form-row>

                    <form-row label="商品属性">
                        <AddAttr :attrList.sync="attrList" :hash.sync="hash"/>
                    </form-row>

                    <form-row label="属性明细">
                        <AttrDetail :attrList="attrList" :hash="hash" @attr="renewAttr"/>
                    </form-row>

                    <form-row :label="`价格`" :required="true">
                        <el-form-item slot="item" class="form-row__item" prop="sale_price">
                            <el-input v-model.number="ruleForm.sale_price" placeholder="请输入价格"
                                      :disabled="hasAttr"></el-input>
                        </el-form-item>
                        <div slot="info-item" class="form-row__item_info">元</div>
                    </form-row>
                    <form-row :label="`是否售卖`" :required="true">
                        <el-form-item slot="item" class="form-row__item" prop="is_on_sale">
                            <el-switch v-model="ruleForm.is_on_sale" active-color="#13ce66" inactive-color="#999999">
                            </el-switch>
                        </el-form-item>
                    </form-row>
                    <form-row :label="`单位`" :required="true">
                        <el-form-item slot="item" class="form-row__item" prop="unit">
                            <el-input v-model.number="ruleForm.unit" placeholder="请输入单位"></el-input>
                        </el-form-item>
                    </form-row>

                    <form-row :label="`库存`" :required="true">
                        <el-form-item slot="item" class="form-row__item" prop="number">
                            <el-input v-model.number="ruleForm.number" placeholder="请输入库存"
                                      :disabled="hasAttr"></el-input>
                        </el-form-item>
                        <div slot="info-item" class="form-row__item_info">以单位中的规格来计算</div>
                    </form-row>
                    <form-row :label="`运费模板`" :required="true">
                        <el-form-item slot="item" class="form-row__item" prop="freight_id">
                            <el-select v-model="ruleForm.freight_id" placeholder="请选择运费模板">
                                <el-option
                                        v-for="item in freightData"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </form-row>
                    <form-row style="border-bottom:none;">
                        <el-form-item slot="item" class="form-row__item_last">
                            <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
                            <el-button @click="resetForm('ruleForm')">重置</el-button>
                        </el-form-item>
                    </form-row>

                </el-form>

            </div>
        </div>
    </section>
</template>

<script>
    import FormRow from '@/components/basic/FlowRow.vue';
    import ImageUpload from '@/components/basic/UploadImage/ImageUpload.vue'
    import Upload from '@/components/basic/UploadImage/Upload.vue';
    import CategoryList from '@/components/basic/CategoryList.vue';
    import AddAttr from './components/AddAttr'
    import AttrDetail from './components/AttrDetail'

    export default {
        components: {
            ImageUpload,
            Upload,
            FormRow,
            CategoryList,
            AddAttr,
            AttrDetail
        },
        data() {
            return {
                hash: Math.random(),
                clearList: null,
                ruleForm: {
                    attributes: [],
                    slideshows: []
                },
                rules: {
                    name: [{required: true, message: '请输入商品名称', trigger: 'blur'}],
                    unit: [{required: true, message: '请输入单位', trigger: 'blur'}]
                },
                attrList: [],
                freightData: []
            }
        },
        computed: {
            hasAttr() {
                return this.ruleForm.attributes.length > 0
            }
        },
        mounted() {
            this.getFreightData()
        },
        methods: {
            getFreightData() {
                axios
                    .get('admin_freights')
                    .then(res => res.data.data)
                    .then(res => {
                        console.log('运费模板', res)
                        this.freightData = res;
                    })
            },
            back() {
                this.$router.go(-1);
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
                this.ruleForm.image = [];
                this.ruleForm.slideshows = [];
                this.ruleForm.attributes = [];
                this.clearList = Math.random();
            },
            submitForm(formName) {

                this.$refs[formName].validate(valid => {
                    if (!valid) return false
                    this.$confirm('是否确认添加商品?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    })
                        .then(() => this.validate(this.ruleForm))
                        // .then(() => this.genData(this.ruleForm))
                        .then(() => this.postData())
                        .then(() => {
                            this.$message({
                                type: 'success',
                                message: '添加成功!'
                            });
                            this.resetForm('ruleForm')
                        })
                        .catch(err => {
                            if (err !== 'cancel') {
                                this.$message({
                                    type: 'error',
                                    message: `添加失败 ${err}`
                                });
                            }
                        });
                });
            },
            validate(data) {

                const {image, slideshows, freight_id} = data;
                if (!image) return Promise.reject('请选择商品详情图');
                if (slideshows.length === 0) return Promise.reject('请选择商品主图');
                if (!freight_id) return Promise.reject('请选择运费模板');

                return data;
            },
            genData(data) {
                var attrNumber = 0;
                if( data.attributes.length > 0 ){
                    for(var i= 0 ; i< data.attributes.length ; i++){
                        attrNumber += parseInt(data.attributes[i].number)
                    }
                }

                const element = {
                    name: data.name,
                    desc: data.desc,
                    number: data.attributes.length === 0 ? data.number : attrNumber,
                    sale_price: data.attributes.length === 0 ? data.sale_price : data.attributes[0].sale_price,
                    unit: data.unit,
                    is_on_sale: data.is_on_sale === true ? 1 : 0,
                    image: data.image,
                    content_images: '',
                    attributes: JSON.stringify(data.attributes),
                    slideshows: data.slideshows.map(res => res.url).join(','),
                    cat_id: '',
                    freight_id: data.freight_id,
                };
                console.log('元素', element)
                return element;
            },
            postData() {
                // console.log('提交')
                return axios
                    .post('admin_goods', this.genData(this.ruleForm))
                    .then(res => {
                        return res.data.status === 1 ? Promise.resolve() : Promise.reject(res.data.msg);
                    });
            },
            // //属性方法
            // isEdit(index) {
            //     this.ruleForm.attributes[index].edit = !this.ruleForm.attributes[index].edit
            // },
            // addAttr() {
            //     this.ruleForm.attributes.push({name: '', sale_price: '', number: '', edit: true})
            // },
            // cancel(index) {
            //     this.ruleForm.attributes.splice(index, 1)
            // },
            // delete(index) {
            //     this.ruleForm.attributes.splice(index, 1)
            // },
            renewAttr(tableData) {
                const requiredKeys = ['sale_price', 'number', 'weight']
                const required = (data, list) => _.pick(data, list)
                const customize = (data, list) => _.omit(data, list)
                const genKey = data => _.map(data, (value, key) => ([key, value]))

                this.ruleForm.attributes = _.map(tableData, item => Object.assign({}, required(item, requiredKeys), {key: genKey(customize(item, requiredKeys))}))
            }
        }
    }
</script>
<style scoped>
    .cate-container {
        min-height: calc(100vh - 92px);
    }

    .flex-box {
        display: flex;
    }

    .header {
        padding: 10px;

        background: #fff;
    }

    .cate-con {
        margin: 10px;
        padding: 20px;

        background: #fff;
    }

    .image-info {
        font-size: 12px;
        color: #666666;
    }
</style>
<style>

</style>